﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Aquarinum.Base.Infrastructure.WebSocket.Interface;
using Aquarinum.WebSocekt.Core.Entitys;

namespace Aquarinum.Base.Infrastructure.WebSocket.InterfaceImp
{
    public class WebSocketConnectionContainer
    {
        private readonly IClientInfosProvider _clientInfosProvider;

        private readonly ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets =
            new ConcurrentDictionary<string, System.Net.WebSockets.WebSocket>();

        //todo
        //public WebSocketConnectionContainer(IClientInfosProvider clientInfosProvider)
        //{
        //    _clientInfosProvider = clientInfosProvider;
        //}

        public bool CheckClientExist(string id)
        {
            if (_sockets.ContainsKey(id)) return GetSocketById(id).State == WebSocketState.Open;

            return false;
        }

        public IList<string> GetAllClient()
        {
            return _sockets.Keys.ToList();
        }

        public System.Net.WebSockets.WebSocket GetSocketById(string id)
        {
            _sockets.TryGetValue(id, out var result);

            return result;
        }


        public ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> GetAll()
        {
            return _sockets;
        }

        public List<ClientEntity> GetAllClientsFromGroup(string groupId)
        {
            //todo return _clientInfosProvider.GetClientsByGroupId(groupId).ToList();
            return new List<ClientEntity>();
        }


        public string GetId(System.Net.WebSockets.WebSocket socket)
        {
            return _sockets.FirstOrDefault(p => p.Value == socket).Key;
        }

        public void AddSocket(string socketId, System.Net.WebSockets.WebSocket socket)
        {
            _sockets.TryRemove(socketId, out _);
            _sockets.TryAdd(socketId, socket);
        }


        public async Task RemoveSocket(string id)
        {
            _sockets.TryRemove(id, out var socket);

            await socket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                "Closed by the WebSocketManager",
                CancellationToken.None).ConfigureAwait(false);
        }
    }
}